<template>
  <div>
    <div class="back"><span @click="back">机构列表></span></div>
    <el-card class="elcard" style="margin-bottom:20px;overflow:initial;">
      <div class="logo-box">
        <img width="100%" height="100%" v-if="srcImg !== ''" :src="srcImg" alt="">
        <img width="100%" height="100%" v-else src="../../../../assets/img/default.png" alt="">
        <!-- <img width="100%" height="100%" src="../../../../assets/img/test-company.png" alt=""> -->
      </div>
      <div class="user-info">
        <h2>{{companyName}}</h2>
        <p class="info1">
          <span>所属地：<i>{{address}}</i></span>
        </p>
        <p class="info2">
          <span>专利数量：<i>{{doc_count}}</i></span>
          <span>论文数量：<i></i></span>
        </p>
      </div>
    </el-card>
    <!-- 专利趋势 -->
    <el-card class="elcard" style="margin-top:20px;">
      <div slot="header" class="clearfix">
        <span class="tit">专利趋势</span>
      </div>
      <div id="chartOne" style="width:100%;height:430px"></div>
    </el-card>
    <!-- 成果转化潜力 -->
    <el-card class="elcard" style="margin-top:20px;">
      <div slot="header" class="clearfix">
        <span class="tit">成果转化潜力</span>
      </div>
      <el-table
        :data="tableData1"
        class="eltable"
        :header-cell-style="headerCellStyle"
        style="width: 100%">
        <el-table-column
          prop="key"
          label="潜在合作内容">
        </el-table-column>
        <el-table-column
          prop="doc_count"
          label="专利数量">
        </el-table-column>
        <el-table-column
          prop="name2"
          label="潜在合作企业">
          <template slot-scope="scope">
            <p v-for="(item, index) in scope.row.companys" :key="index" :title="item" class="wrap">{{item}}</p>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="percentage"
          label="匹配程度"
          width="220">
          <template slot-scope="scope">
            <div class="percentage-box">
              <el-progress :stroke-width="10" :show-text="false" :percentage="scope.row.percentage" :color="customColors" class="progress"></el-progress>
              <p class="number">{{scope.row.percentage}}
                ({{scope.row.percentage > 80 ? '高' : 
                  scope.row.percentage > 50 ? '中' : '低'}})</p>
            </div>
          </template>
        </el-table-column> -->
      </el-table>
      <!-- <el-col :span="24" style="text-align:center;padding:10px; 0">
        <el-pagination
          background
          @current-change="handleCurrentChange1"
          layout="prev, pager, next"
          :current-page.sync="ipi1"
          :page-size="ips"
          :total="total1">
        </el-pagination>
      </el-col> -->
    </el-card>
    <!-- 产学研合作情况 -->
    <el-card class="elcard" style="margin-top:20px;">
      <div slot="header" class="clearfix">
        <span class="tit">产学研合作情况</span>
      </div>
      <el-table
        :data="tableData2"
        class="eltable"
        @row-click="showCount"
        :header-cell-style="headerCellStyle"
        :row-style="{'cursor': 'pointer'}"
        style="width: 100%">
        <!-- <el-table-column
          prop="src"
          label="科研机构名称">
        </el-table-column> -->
        <el-table-column
          prop="target"
          label="企业名称">
          <template slot-scope="scope">
            <p :title="scope.row.target" class="wrap">{{scope.row.target}}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="info_title"
          label="合作内容">
          <template slot-scope="scope">{{scope.row.info[0].title}}</template>
        </el-table-column>
        <el-table-column
          prop="info_ad"
          label="时间"
          width="220">
          <template slot-scope="scope">{{scope.row.info[0].ad}}</template>
        </el-table-column>
        <el-table-column
          prop="count"
          label="涉及专利数"
          width="140">
          <template slot-scope="scope">
            <p>{{scope.row.count}}</p>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-col :span="24" style="text-align:center;padding:10px; 0">
        <el-pagination
          background
          @current-change="handleCurrentChange1"
          layout="prev, pager, next"
          :current-page.sync="ipi2"
          :page-size="ips"
          :total="total2">
        </el-pagination>
      </el-col> -->
    </el-card>
    <!-- 合作关系图 -->
    <el-card class="elcard" style="margin-top:20px;">
      <div slot="header" class="clearfix">
        <span class="tit">合作关系图</span>
      </div>
      <div class="chart-box">
        <div id="chartTwo" style="width:100%;height:600px;"></div>
        <p v-if="chartTwoData.length<=0" class="no-data">{{noData}}</p>
      </div>
    </el-card>
    <!-- 专利详情弹窗 -->
    <vDialogPn ref="vDialogPn"/>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import resize from '@/utils/resize'
import Colors from '@/utils/chartsColors'
import axios from 'axios'
import vDialogPn from '@/views/components/v-dialog-pn'
export default {
  mixins:[resize],
  data() {
    return {
      companyName: this.$route.query.name,
      eid: this.$route.query.eid,
      address: '',
      srcImg: '',
      doc_count: this.$route.query.doc_count || '',
      isCompany: this.$route.query.isCompany || false,
      chartOne: null,
      chartTwo: null,
      tableData1: [],
      ipi1: 1,
      ips: 5,
      total1: 0,
      customColors: [
        {color: '#f06e6e', percentage: 0},
        {color: '#efa752', percentage: 50},
        {color: '#74cec1', percentage: 80},
      ],
      tableData2: [],
      ipi2: 1,
      total2: 0,

      dialogVisible: false,
      // tableData3: [],
      tableData3All: [],
      // ipi3: 1,
      // total3: 0,
      // 合作关系图
      chartTwoData: [],
      noData: '图表生成中...'
    }
  },
  components: {
    vDialogPn
  },
  beforeRouteEnter(to, from, next) {
    next(vm=>{          //  这里的vm指的就是vue实例，可以用来当做this使用
      if(from.name){
        vm.routerParameter = from.name
      }
    })
  },
  computed:{
    ...mapState(['levelCode','levelName']),
    routerParameter:{
      get: function() {
        return this.$store.state.routerParameter;
      },
      set: function(newValue) {
        this.$store.commit("setRouterParameter", newValue);
      }
    }
  },
  methods: {
    init() {
      // 判断专利量
      if(!this.$route.query.doc_count){
        this.$post(this.$Url.production.cityAnalysis,{
          "aggs": {
            "size": "10",
            "field": "patent_type",
            "type": "base"
          },
          "musts": {
              "an1": this.$route.query.companyName
          },
          code: this.levelCode
        }).then(res=>{
          if(res.data){
            let total = 0
            res.data.forEach(i => {
              total+=i.doc_count
            });
            this.doc_count = total
          }
        }).catch(e=>{console.log(e)})
      }
      this.getImg()
      this.getAddress()
      this.getTableData1()
      this.getTableData2()
    },
    getImg() {
      this.$get(this.$Url.search.companyLogo, {
        eid: this.eid
      }).then(res => {
        let data = res.data
        if (data) {
          this.srcImg = data
        }
      }).catch(err => {})
    },
    getAddress() {
      this.$get(this.$Url.company.address, {
        eid: this.eid
      }).then(res => {
        let data = res.data
        if (data && data.length > 0) {
          this.address = data[0] && data[0].address
        }
      }).catch(err => {})
    },
    // 趋势
    getAnalysis(field) {
      return this.$post(this.$Url.production.analysis, {
        companyName: this.companyName,
        musts: {
          date_sort: "1"
        },
        rangArr: [
          {
            field: field,
            start: this.$DateManag().start,
            end: this.$DateManag().end
          },
        ],
        aggs: {
          interval: "YEAR",
          format: "yyyy",
          field: field,
          type: "date"
        }
      })
    },
    getChartOneData() {
      this.chartOne.showLoading({
        text: 'loading',
        color: '#0b0a2b',
        textColor: '#0b0a2b',
        maskColor: '#fff',
        zlevel: 0
      })
      axios.all([this.getAnalysis('ad'), this.getAnalysis('isd')]).then(axios.spread((res1, res2) => {
        let data1 = res1.data || []
        let data2 = res2.data || []
        let xAxisData = []
        let yAxisData1 = []
        let yAxisData2 = []
        for (let i in data1) {
          xAxisData.push(data1[i].key_as_string)
          // yAxisData1.push(data1[i].doc_count)
        }
        for (let i in data2) {
          xAxisData.push(data2[i].key_as_string)
          // yAxisData2.push(data2[i].doc_count)
        }
        let endYear = String(this.$DateManag().end).split('-')[0]
        xAxisData = Array.from(new Set(xAxisData))
        xAxisData.sort((a, b) => {
          return Number(a) - Number(b)
        })

        for (let i in xAxisData) {
          let number1 = 0
          let number2 = 0
          for (let j1 in data1) {
            if (data1[j1].key_as_string === xAxisData[i]) {
              number1 = data1[j1].doc_count
            }
          }
          for (let j2 in data2) {
            if (data2[j2].key_as_string === xAxisData[i]) {
              number2 = data2[j2].doc_count
            }
          }
          yAxisData1.push(number1)
          yAxisData2.push(number2)
        }
        
        if (xAxisData[xAxisData.length - 1] !== endYear) {
          xAxisData.push(endYear)
          yAxisData1.push(0)
          yAxisData2.push(0)
        }
        let d = (name, index, data) => {
          let solid = [...data.slice(0, data.length - 1), '-']
          let dotted = []
          for (let i in data) {
            if (i < data.length - 2) {
              dotted.push('-')
            } else {
              dotted.push(data[i])
            }
          }
          return [{ // 实线
            type: 'line',
            name: name,
            color: Colors.color[index],
            data: solid,
            areaStyle: {
              normal: {
                type: 'radial',
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                      offset: 0, color: "rgba(" + Colors.rgb[index] + ",0.3)" // 0% 处的颜色
                  }, {
                      offset: 1, color: "rgba(" + Colors.rgb[index] + ",0.01)" // 100% 处的颜色
                  }],
                  global: false // 缺省为 false
                },
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowBlur: 10
              }
            }
          }, { // 虚线
            type: 'line',
            name: name,
            color: Colors.color[index],
            data: dotted,
            lineStyle: {
              type: 'dotted'
            },
            areaStyle: {
              normal: {
                type: 'radial',
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                      offset: 0, color: "rgba(" + Colors.rgb[index] + ",0.3)" // 0% 处的颜色
                  }, {
                      offset: 1, color: "rgba(" + Colors.rgb[index] + ",0.01)" // 100% 处的颜色
                  }],
                  global: false // 缺省为 false
                },
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowBlur: 10
              }
            }
          }]
        }

        let seriesData = [...d('申请数量', 0, yAxisData1), ...d('公开数量', 1, yAxisData2)]
        this.renderChartOne(xAxisData, seriesData)
      }))
    },
    renderChartOne(xAxisData, seriesData) {
      let option = {
        tooltip: {
          confine: true,
          trigger: "axis",
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderRadius: 0,
          padding: 5,
          textStyle: {
              color: "#000"
          },
          axisPointer: { type: "none" },
          formatter: function (params, ticket, callback) {
            var htmlStr = '';
            var valMap = {};

            htmlStr += (params[0].name ||  params[3].name)+ '<br/>';//x轴的名称
            
            for(var i=0;i<params.length;i++){
              var param = params[i];
              var xName = param.name;//x轴的名称
              var seriesName = param.seriesName;//图例名称
              var value = param.value;//y轴值
              var color = param.color;//图例颜色
              //过滤无效值
              if(value == '-'){
                continue;
              }
              //过滤重叠值
              if(valMap[seriesName] == value){
                continue;
              }
              htmlStr +='<div>';
              //为了保证和原来的效果一样，这里自己实现了一个点的效果
              htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:'+color+';"></span>';
              //圆点后面显示的文本
              htmlStr += seriesName + '：' + value;
              htmlStr += '</div>';
              valMap[seriesName] = value;
            }
            return htmlStr;
          }
        },
        legend: {
          type: "scroll",
          top: '0'
        },
        grid: {
          top: '50'
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: xAxisData,
          splitLine: {
          show: false,
            lineStyle: {
              color: "#f0f1f3"
            }
          },
          axisLine: {
            lineStyle: {
              color: "#f0f1f3",
              width: 2
            }
          },
          axisLabel: {
            textStyle: {
              color: "#9e9e9e"
            }
          }
        },
        yAxis: {
          type: "value",
          splitLine: {
            show: true,
            lineStyle: {
                color: "#f0f1f3"
            }
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
                color: "#f0f1f3",
                width: 2
            }
          },
          axisLabel: {
            textStyle: {
                color: "#9e9e9e"
            }
          }
        },
        dataZoom: [
          {
            id: 'dataZoomX',
            type: 'inside',
            xAxisIndex: [0],
            filterMode: 'filter'
          }
        ],
        series: seriesData
      }
      this.chartOne.hideLoading()
      this.chartOne.setOption(option, true)
    },
    getchartTwoData(res) {
      let data = res.data || []
      if (data.length > 0) {
        this.chartTwoData = JSON.parse(JSON.stringify(data))
        let link = []
        let node = []
        // 取关系
        for(let i in data){
          node.push(data[i].src)
          node.push(data[i].target)
          if (data[i].src !== data[i].target) { // 图表不允许出现重复的节点，所以做下去重
            link.push({
              source: data[i].src,
              info:data[i].info,
              target: data[i].target,
              value: data[i].count
            })
          }
          
        }
        // 取节点
        node = Array.from(new Set(node))
        let nodejson = []
        for(let i in node){
          nodejson.push({
            name: node[i]
          })
        }
        this.renderchartTwo(nodejson, link)
      } else {
        this.noData = '暂无数据'
      }
    },
    renderchartTwo(node, link) {
      let option = {
        title: {
          show: false
        },
        tooltip: {
          trigger: 'item',
          triggerOn: 'mousemove'
        },
        color: Colors.color,
        series: [
          {
            type: 'sankey',
            data: node,
            left: 30,
            right: 230,
            links: link,
            draggable:false,
            focusNodeAdjacency: false,
            itemStyle: {
                borderWidth: 1,
                borderColor: '#aaa',
                fontSize: '10px'
            },
            lineStyle: {
                color: 'source',
                curveness: 0.5
            },
            lable:{
                fontSize:'9'
            }
          }
        ]
      }
      this.chartTwo.setOption(option)
      let that = this
      this.chartTwo.on('click',function(prim){
        if(prim.dataType === 'node'){
          isComapny(prim.name)
        }else{
          if(prim.data.info) that.$refs.vDialogPn.init(prim.data.info)
        }
      })
      
      // 判断机构或者是企业
      function isComapny(name){
        let eid =''
        that.$get(that.$Url.company.getCompanyId, {
          keyWord: name
        }).then((res) => {
          let datas = res.data
          if(datas){
            eid = datas.result[0]._id
            that.$get(`${that.$Url.organization.isComapny}/?eid=${eid}`,{})
            .then(data=>{
              // console.log(data)
              // true 是公司
              if(data.data == true){
                let val = {name:name,type:'company',eid:eid}
                that.$Bus.$emit("progressBar", val)
              }
            }).catch(e=>{console.log(e)})
          }
        }).catch(e=>{console.log(e)})
      }
    },
    handleCurrentChange1() {

    },
    // 成果转化潜力
    getTableData1() {
      this.$post(this.$Url.production.transform, {
        aggs: {
          size: "10",
          field: "ipc_kind",
          type: "base"
        },
        name: this.companyName,
        code: this.levelCode
      }).then(res => {
        this.tableData1 = res.data || []
      }).catch(err => {})
    },
    // 产学研合作
    getTableData2() {
      this.$post(this.$Url.production.teamwork, {
        aggs: {
          size: "20",
          field: "an",
          type: "base",
          subAggs: {
            size: "1000",
            field: "pn",
            type: "base"
          }
        },
        name: this.companyName,
        code: this.levelCode,
        musts: {
          date_sort: "1"
        }
      }).then(res => {
        let data = res.data || []
        data.forEach(v => {
          v.info_title = v.info[0].title
          v.info_ad = v.info[0].ad
        })
        this.tableData2 = data
        this.getchartTwoData(res)
      }).catch(err => {})
    },
    showCount(row) {
      this.$refs.vDialogPn.init(row.info)
    },
    headerCellStyle() {
      return {
        'font-weight': 'normal',
      }
    },
    // 返回上一页
    back() {
      window.history.back()
    }
  },
  mounted() {
    this.chartOne = this.$echarts.init(document.getElementById('chartOne'))
    this.chartTwo = this.$echarts.init(document.getElementById('chartTwo'))
    this.init()
    this.getChartOneData()
    // this.getchartTwoData()
  }
}
</script>

<style lang="scss" scoped>
.back{
  padding-bottom:20px;
  padding-left:10px;
  text-align: right;
  span {
    cursor: pointer;
  }
}
.elcard {
  position: relative;
  margin-bottom: 20px;
  text-align: left;
  .tit {
    font-size: 14px;
    font-weight: bold;
  }
  .logo-box {
    position: absolute;
    top: 20px;
    left: 20px;
    width: 120px;
    height: 120px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
  }
  .user-info {
    position: relative;
    min-height: 120px;
    padding-left: 140px;
    padding-right: 40px;
    text-align: left;
    h2 {
      line-height: 30px;
      margin-bottom: 10px;
      font-weight: bold;
      font-size: 18px;
      color: #4f515b;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .info1 {
      position: relative;
      display: inline-flex;
      align-items: center;
      width: 100%;
      line-height: 24px;
      padding: 4px 0;
      font-size: 14px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      span {
        flex: .5;
        color: #86899e;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        i {
          font-style: normal;
          color: #4f515b
        }
      }
    }
    .info2 {
      position: relative;
      display: inline-flex;
      align-items: center;
      width: 100%;
      line-height: 24px;
      padding: 4px 0;
      font-size: 14px;
      color: #86899e;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      span {
        flex: .33;
        color: #86899e;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        i {
          font-style: bold;
          color: #504da5
        }
      }
    }
  }
  .percentage-box {
    display: flex;
    align-items: center;
    justify-content: center;
    .progress {
      flex: .4
    }
    .number {
      flex: .5;
      margin-left: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  // .main-box {
  //   display: flex;
  //   .left-box {
  //     flex: .5;
  //     .tit {
  //       display: inline-block;
  //       width: 56px;
  //       text-align: left;
  //       font-size: 12px;
  //       color: #4f515b;
  //     }
  //     .elselect {
  //       width: 200px;
  //       background-color: #f3f5f8;
  //     }
  //     .eldatepicker {
  //       width: 120px;
  //     }
  //     .split {
  //       display: inline-block;
  //       padding: 0 5px;
  //     }
  //   }
  // }
  
}
.wrap {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.chart-box {
  position: relative;
  width: 100%;
}
.no-data {
  position: absolute;
  top: 0;
  left: 0;
}
</style>